<?php

namespace app\admin\business;

use app\common\model\mysql\Category as CategoryModel;
use think\Exception;
use think\Log;

class Category
{
    public $Model = null;

    public function __construct()
    {
        $this->Model = new CategoryModel;
    }
    public function add($data)
    {
        if (empty($data)) {
            return false;
        }
        // 验证分类名称不冲突
        $category_name = $this->Model->getCategoryByName($data['name']);
        if (!empty($category_name)) {
            throw new Exception("该分类名已存在，请重新输入");
        }

        try {
            $res = $this->Model->save($data);
        } catch (\Exception $e) {
            throw new Exception("服务器内部异常");
        }
        return $this->Model->id;
    }

    public function getNormalCategorys()
    {
        $field = 'id,name,pid';
        $categorys = $this->Model->getNormalCategorys($field);
        if (!$categorys) {
            return $categorys;
        }
        return $categorys->toArray();
    }

    public function getNormalAllCategorys()
    {
        $field = 'id as category_id,name,pid';
        $categorys = $this->Model->getNormalCategorys($field);
        if (!$categorys) {
            return $categorys;
        }
        return $categorys->toArray();
    }

    public function getList($data, $num) {
        $list = $this->Model->getList($data, $num);
//        dump($list->toArray());exit();
        if(!$list) {
            return [];
        }

        $result = $list->toArray();
        $result['render'] = $list->render();

        // 思路： 第一步拿到列表中id 第二步：in mysql 求count  第三步：把count填充到列表页中

        $pids = array_column($result['data'], "id");
//        dump($pids);

        if($pids) {
            $idCountResult = $this->Model->getChildCountInPids(['pid' => $pids]);
//            dump($idCountResult->toArray());
            $idCountResult = $idCountResult->toArray(); //  如果没有的话会返回空数组
//
            $idCounts = [];
            // 第一种方式
            foreach($idCountResult as $countResult) {
                $idCounts[$countResult['pid']] = $countResult['count'];
            }
        }
//        dump($idCounts);

        if($result['data']) {
            foreach($result['data'] as $k => $value) {
                /// $a ?? 0 等同于 isset($a) ? $a : 0。
                $result['data'][$k]['childCount'] = $idCounts[$value['id']] ?? 0;
            }
        }
//        dump($result);
        return $result;
    }

    public function getList1($data, $page)
    {
        $dataList = $this->Model->getList($data, $page);
        if (!$dataList) {
            $dataList = [];
        }
        $result = $dataList->toArray();
        $result['render'] = $dataList->render();

        // 思路：第一步拿到列表的ID，第二步 in mysql 求count, 第三步 把count填充到列表页中

        $pids = array_column($result['data'], 'id');
        $dataList = ['pid' => $pids];
        if ($pids) {
            $idChildLists = $this->Model->getChildList($dataList);
            $idChildLists = $idChildLists->toArray();
            $idCounts = [];
            foreach ($idChildLists as $childList) {
                $idCounts[$idChildLists['pid']] = $childList['count'];
            }
        }
        if ($result['data']) {
            foreach ($result['data'] as $k => $value) {
                $result['data'][$k]['childCount'] = $idCounts[$value['id']] ?? 0;
            }
        }

        return $result;
    }

    public function test($data)
    {

        $idChildLists = $this->Model->getTest($data);
//        dump($idChildLists->toArray());
        $res = $idChildLists->toArray();
        return $res;

    }

    public function getByID($id)
    {
        if (!$id) {
            throw new Exception("不存在该记录");
        }
        $result = $this->Model->find($id);
        if (empty($result)) {
            return [];
        }
        return $result->toArray();
    }

    public function getListorder($id, $listorder)
    {
        // 是否存在这个ID对应的数据
        $result = $this->getByID($id);
        if (!$result) {
            throw new Exception("不存在该记录");
        }
        $data = [
            'list_order' => $listorder,
        ];

        $list = $this->Model->updateById($id, $data);
        if (!$list) {
            $list = false;
        }
        return $list;
    }

    public function getStatus($id, $status)
    {
        // 是否存在该ID对应的数据
        $result = $this->getByID($id);
        if (!$result) {
            throw new Exception("不存在该记录");
        }

        if ($result['status'] == $status) {
            throw new Exception("状态修改前后一致，请重试");
        }
        $data = [
            'status' => intval($status)
        ];

        $res = $this->Model->updateByStatus($id, $data);
        if (!$res) {
            $res = false;
        }
        return $res;
    }

    public function getNormalByPid($pid = 0, $field = "id, name, pid")
    {
        try {
            $res = $this->Model->getNormalByPid($pid, $field);
        } catch (\Exception $e) {
            throw new Exception("内部异常");
        }
        return $res->toArray();
    }
}